
var authorization = "Bearer " + getCookie('Admin-Token');
var cellrelations = {};
var currEditCell = null;
var currEditCellValue = null;
var protectFormFlag = false;
var protectCellData = {};
var maxFileSize = 3072;
var userId = "";
var celldata = [];
//数据库映射树
var zDbTree = null;
//zTree参数配置
var dbTreeSetting = {
    data: {
        simpleData: {
            enable: true,
			idKey: "id",
			pIdKey: "pId",
			rootPId: "dbRoot"
        }
    },
    check: {
		enable: true,
		chkStyle: "checkbox"
	}
};

function getUrl(uri) {
    //兼容vue不同环境代理前缀不同
    let currenv = JSON.parse(window.localStorage.getItem("currenv"));
    let urlprefix = currenv.VUE_APP_BASE_API;
    return urlprefix + uri;
}

function getCookie(name) {
    let nameEQ=name+"=";
    let str=document.cookie.split(';');
    for(let i=0;i<str.length;i++){
      let c=str[i];
      while(c.charAt(0)==' '){
        c=c.substring(1,c.length);
      }
      if(c.indexOf(nameEQ)==0){
        return decodeURIComponent(c.substring(nameEQ.length,c.length));
      }
    }
    return "";
}

function initPluginsSelect(pluginServiceTypes){
    if(pluginsInfo!=undefined&&pluginsInfo!=null&&pluginsInfo.length>0){
        $("#selectedPlugins")[0].options.length=0;
        let options = "";
        for(let a=0;a<pluginsInfo.length;a++){
            options += "<option value='" + pluginsInfo[a].pluginId + "'>" + pluginsInfo[a].showName + "</option>";
            initDynamicPlugin(pluginsInfo[a],pluginServiceTypes);
        }
        $("#selectedPlugins").append(options);
    }
}

function hideAllPlugins(){
    if(pluginsInfo!=undefined&&pluginsInfo!=null&&pluginsInfo.length>0){
        for(let a=0;a<pluginsInfo.length;a++){
            $("#" +  pluginsInfo[a].pluginId).hide();
        }
    }
}

function showSelectedPlugin(pluginId){
    if(pluginsInfo!=undefined&&pluginsInfo!=null&&pluginsInfo.length>0){
        for(let a=0;a<pluginsInfo.length;a++){
            if(pluginId==pluginsInfo[a].pluginId){
                $("#" + pluginId).show();
            }else{
                $("#" +  pluginsInfo[a].pluginId).hide();
            }
        }
    }
}

function loadSysCustomPlugins(rowSelect,columnSelect){
    initPluginsSelect(null);
    backPlugins();
    let currSheetName = luckysheet.getSheet().name;
    let cellCoord = currSheetName + "_" + rowSelect + "_" + columnSelect;
    let selectedPluginId = cellrelations[cellCoord];

    if(selectedPluginId!=undefined&&selectedPluginId!=null&&selectedPluginId.length>0){
        $("#selectedPlugins option[value='" + selectedPluginId + "']").attr("selected",true);
    }

    layui.use(['form'], function(){
        var form = layui.form;
        form.render('select');
    });

    showSelectedPlugin(selectedPluginId);
    $("#pluginsSelect").show();

    layer.open({
        title: "系统插件",
        type: 1,
        area: ['500px', '300px'],
        content: $('#extendPlugins') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
        ,btn: ['选择插件', '删除插件']
        ,yes: function(index, layero){
            let pluginId = $("#selectedPlugins option:selected").val();
            if("0"!=pluginId){
                cellrelations[cellCoord] = pluginId;
            }else{
                delete cellrelations[cellCoord];
            }
            $("#pluginsSelect").hide();
            hideAllPlugins();
            layer.close(index);
        }
        ,btn2: function(index, layero){
            //按钮【按钮二】的回调
            if(cellrelations.hasOwnProperty(cellCoord)){
                delete cellrelations[cellCoord];
            }
            $("#pluginsSelect").hide();
            hideAllPlugins();
        }
        ,cancel: function(index, layero){
            $("#pluginsSelect").hide();
            hideAllPlugins();
        }
    });
}

var uploadInst = null;
let uploadRow = '';
let uploadCol = '';
function sysFileUpload(rowSelect,columnSelect){
    uploadRow = rowSelect;
    uploadCol = columnSelect;

    $("#cellFileSelect").show();

    let fileName = "";
    let reFileName = "xmps_";
    layui.use('upload', function() {
        var $ = layui.jquery
            , upload = layui.upload;

        if(uploadInst==null){
            uploadInst = upload.render({
                elem: '#test10'
                ,accept: 'file' //images（图片）、file（所有文件）、video（视频）、audio（音频）
                ,exts: 'jpg|jpeg|png|bmp|doc|docx|xls|xlsx|pdf' //可传输文件的后缀
                ,drag: false
                ,auto: false
                ,bindAction: "#testListAction"
                ,size: maxFileSize
                ,choose: function(obj){
                    reFileName = "xmps_";
                    var timestamp = new Date().getTime();
                    if(userId!=undefined&&userId!=null&&userId.length>0){
                        reFileName += userId + "_" + timestamp;
                    }else{
                        reFileName += + timestamp;
                    }
                    obj.preview(function(index, file, result){
                        fileName = file.name;
                        reFileName += fileName.substr(fileName.indexOf("."));
                        $('#uploadDemoView').show();
                        $('#filename').text(fileName);

                        uploadInst.reload({
                            url: "/api/v3/file/projectReview?fileName=" + reFileName
                        });
                    });
                }
                ,done: function(res){
                    layer.msg('上传成功');
                    let cellUpdate = {
                        "v": res.url, //内容的原始值
                        "m": res.originalName, //内容的显示值
                    };
                    luckysheet.setCellValue(uploadRow,uploadCol,cellUpdate);
                }
                ,error: function(index, upload){
                    layer.msg('上传失败');
                }
            });
        }

        layer.open({
            title: "文件上传",
            type: 1,
            area: ['480px', '300px'],
            content: $('#selectFile') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            ,cancel: function(index, layero){
                $("#cellFileSelect").hide();
                $('#uploadDemoView').hide();
                $('#filename').text('');
            }
        });
    });
}

function sysFileDownLoad(rowSelect,columnSelect){
    let currV = luckysheet.getCellValue(rowSelect, columnSelect);//当前实际值
    let currM = luckysheet.getCellValue(rowSelect, columnSelect, {type:"m"});//当前显示值
    window.location.href = '/api/v3/file/projectReview/get/' + currV;
}

layui.use(['form'], function(){
    let form = layui.form;
    form.on('select(showSelectedPlugin)', function(data){
        let pluginId = data.value;
        if(pluginId==undefined||pluginId==null||pluginId.length==0||"0"==pluginId){
            hideAllPlugins();
        }else{
            showSelectedPlugin(pluginId);
        }
    });
});

function cellEditOper(cell){
    currEditCell = cell[0];
    let currSheetName = luckysheet.getSheet().name;
    let rowSelect = Number(currEditCell.row_focus);
    let columnSelect = Number(currEditCell.column_focus);
    let cellCoord = currSheetName + "_" + rowSelect + "_" + columnSelect;
    let selectedPluginId = cellrelations[cellCoord];
    if(selectedPluginId!=undefined&&selectedPluginId!=null&&selectedPluginId.length>0){
        showSelectedPlugin(selectedPluginId);
        $("#pluginsSelect").hide();
        backPlugins();
        var valueSelect = luckysheet.getCellValue(rowSelect, columnSelect);
        if(valueSelect!=undefined&&valueSelect!=null&&valueSelect.length>0){
            for(let a=0;a<pluginsInfo.length;a++){
                let pluginId =  pluginsInfo[a].pluginId;
                let groupName =  pluginsInfo[a].groupName;
                let pluginType =  pluginsInfo[a].pluginType;
                if(pluginId!=undefined&&pluginId!=null&&pluginId.length>0&&pluginId!="0"){
                    if(selectedPluginId==pluginId){
                        if("radio"==pluginType){
                            $("input[name='" + groupName + "'][value='" + valueSelect + "']").prop("checked",true);
                        }else if("checkbox"==pluginType){
                            let valueSelects = valueSelect.split(",");
                            for(let b=0;b<valueSelects.length;b++){
                                $("input[name='" + groupName + "'][value='" + valueSelects[b] + "']").prop("checked",true);
                            }
                        }else if("select"==pluginType){
                            $("select[name=" + groupName + "]").val(valueSelect);
                        }
                        //----回显树形数据start----
                        if("treecountry"==pluginId){
                            layui.use(['tree'], function(){
                                let tree = layui.tree;
                                let valueSelects =valueSelect.split(",");
                                tree.setChecked('countryTreeId', valueSelects); //勾选指定节点
                            });
                        }
                        if("treesubject2"==pluginId){
                            layui.use(['tree'], function(){
                                let tree = layui.tree;
                                let valueSelects =valueSelect.split(",");
                                let arr = new Array();
                                for(let i=0;i<valueSelects.length;i++){
                                    arr.push(valueSelects[i].split("-")[1]);
                                }
                                tree.setChecked('subject2TreeId', arr); //勾选指定节点
                            });
                        }
                        if("treesubject3"==pluginId){
                            layui.use(['tree'], function(){
                                let tree = layui.tree;
                                let valueSelects =valueSelect.split(",");
                                let arr = new Array();
                                for(let i=0;i<valueSelects.length;i++){
                                    arr.push(valueSelects[i].split("-")[2]);
                                }
                                tree.setChecked('subject3TreeId', arr); //勾选指定节点
                            });
                        }
                        //----回显树形数据end----
                        break;
                    }
                }
            }
            layui.use(['form'], function(){
                let form = layui.form;
                form.render();
            });
        }

        layer.open({
            title: "请选择",
            type: 1,
            area: ['500px', '300px'],
            content: $('#expends'),
            closeBtn: 0
            ,btn: ['确定', '取消']
            ,yes: function(index, layero){
                hideAllPlugins();
                let checkedData = null;
                let code = "";
                let value = "";
                layui.use(['form','tree'],function(){
                    let tree = layui.tree;
                    //树结构选择事件
                    if("treecountry"==selectedPluginId){
                        checkedData = tree.getChecked('countryTreeId'); //获取选中节点的数据
                        if(checkedData!=undefined && checkedData!=null && checkedData.length>0){
                            for(let i=0;i<checkedData.length;i++){
                                let childrenList = checkedData[i].children;
                                for(let j=0;j<childrenList.length;j++){
                                    code = code + ","+childrenList[j].id;
                                    value = value + ",   "+childrenList[j].title;
                                }
                            }
                        }
                    }
                    if("treesubject2"==selectedPluginId){
                        checkedData = tree.getChecked('subject2TreeId'); //获取选中节点的数据
                        if(checkedData!=undefined && checkedData!=null && checkedData.length>0){
                            for(let i=0;i<checkedData.length;i++){
                                let childrenList = checkedData[i].children;
                                for(let j=0;j<childrenList.length;j++){
                                    code = code + ","+checkedData[i].id+"-"+childrenList[j].id;
                                    value = value + ",   "+checkedData[i].title+"-"+childrenList[j].title;
                                }
                            }
                        }
                    }
                    if("treesubject3"==selectedPluginId){
                        checkedData = tree.getChecked('subject3TreeId'); //获取选中节点的数据
                        if(checkedData!=undefined && checkedData!=null && checkedData.length>0){
                            for(let i=0;i<checkedData.length;i++){
                                let childrenList = checkedData[i].children;
                                for(let j=0;j<childrenList.length;j++){
                                    let childrenList2 = childrenList[j].children;
                                    for(let k=0;k<childrenList2.length;k++){
                                        code = code + ","+checkedData[i].id+"-"+childrenList[j].id+"-"+childrenList2[k].id;
                                        value = value + ",   "+checkedData[i].title+"-"+childrenList[j].title+"-"+childrenList2[k].title;
                                    }
                                }
                            }
                        }
                    }
                });
                code = code.substr(1);
                value = value.substr(4);
                let row_focus = Number(currEditCell.row_focus);
                let column_focus = Number(currEditCell.column_focus);
                let cellUpdate = {
                    "v": code, //内容的原始值
                    "m": value, //内容的显示值
                };
                luckysheet.exitEditMode();
                if("treecountry"==selectedPluginId || "treesubject2"==selectedPluginId || "treesubject3"==selectedPluginId){
                    luckysheet.setCellValue(row_focus,column_focus,cellUpdate);//必须放在luckysheet.exitEditMode();之后
                }
                //数据的显示值和实际值的bug转换
                let jsonArr = luckysheet.getAllSheets();
                for(let i=0;i<jsonArr.length;i++){
                    celldata[i] = jsonArr[i].celldata;
                }
                layer.close(index);
            }
            ,btn2: function(index, layero){
                hideAllPlugins();
                luckysheet.exitEditMode();
            },cancel: function(index, layero){
                hideAllPlugins();
                luckysheet.exitEditMode();
            }
        });
    }
}

function dbmapCellEditOper(cell){
    currEditCell = cell[0];
    let selectedPluginId = "treedbmap";
    showSelectedPlugin(selectedPluginId);
    $("#pluginsSelect").hide();
    backPlugins();
    //默认选中
    let fillType = "$";     //填充标志，默认：选中单元格
    let isRequired = "*";   //是否必填，默认：是
    let currFillValue = null;
    let currCellValueV = currEditCellValue.v;
    let currCellValueM = currEditCellValue.m;
    if(currCellValueM!=undefined&&currCellValueM!=null&&currCellValueM.length>0) {
        fillType = currCellValueM.substring(0,1);
        isRequired = currCellValueM.substring(1,2);
        currFillValue = currCellValueV;
    }
    let treeObj = $.fn.zTree.getZTreeObj("treeDbMapId");
    let checkedData = treeObj.getCheckedNodes(true);
    if(checkedData!=undefined&&checkedData!=null&&checkedData.length>0){
        for(let i=0;i<checkedData.length;i++){
            treeObj.checkNode(checkedData[i], false, true);
        }
    }

    $("input[name='tree-dbmap-type'][value='" + fillType + "']").prop("checked",true);
    $("input[name='tree-dbmap-required'][value='" + isRequired + "']").prop("checked",true);
    layui.use(['form'], function(){
        let form = layui.form;
        form.render();
        form.on('radio(cellDbMapType)', function(cell){
            fillType = cell.value;
        });
        form.on('radio(cellDbMapRequired)', function(cell){
            isRequired = cell.value;
        });
        //根据已选择的值设置勾选项
        
        if(currFillValue!=undefined&&currFillValue!=null&&currFillValue.length>0) {
            let currFillValues = currFillValue.split(",");
            currFillValues.forEach(function(data){
                console.log(data);
                let node = treeObj.getNodeByParam("id", data, null);
                console.log(node);
                treeObj.checkNode(node, true, true);
            });
        }
    });
    layer.open({
        title: "请选择",
        type: 1,
        area: ['490px', '530px'],
        content: $('#expends'),
        closeBtn: 0
        ,btn: ['确定', '取消']
        ,yes: function(index, layero){
            hideAllPlugins();
            checkedData = treeObj.getCheckedNodes(true);
            console.log(checkedData);
            let str = "";
            let row_focus = Number(currEditCell.row_focus);
            let column_focus = Number(currEditCell.column_focus);
            if(checkedData!=undefined && checkedData!=null && checkedData.length>0){
                for(let i=0;i<checkedData.length;i++){
                    let pId = checkedData[i].pId;
                    let id = checkedData[i].id;
                    if(pId!=="dbRoot"){
                        str += "," + id;
                    }
                }
                str = str.substring(1,str.length);
                let fillValue = fillType + isRequired + "{" + str + "}";
                let cellUpdate = {
                    "v": str, //内容的原始值
                    "m": fillValue //内容的显示值
                };
                luckysheet.exitEditMode();
                luckysheet.setCellValue(row_focus,column_focus,cellUpdate);
            }else{
                let cellUpdate = {
                    "v": "", //内容的原始值
                    "m": "" //内容的显示值
                };
                luckysheet.exitEditMode();
                luckysheet.setCellValue(row_focus,column_focus,cellUpdate);
            }
            layer.close(index);
        }
        ,btn2: function(index, layero){
            hideAllPlugins();
            luckysheet.exitEditMode();
        },cancel: function(index, layero){
            hideAllPlugins();
            luckysheet.exitEditMode();
        }
    });
}

var optionsTemplete = {
    lang: 'zh', // 设定表格语言
    container: 'luckysheet', //luckysheet为容器id
    title: 'dsas', // 设定表格名称
    column: 16,//默认列数
    row: 20,//默认行数
    autoFormatw: false,//自动格式化超过4位数的数字为‘亿万格式’
    forceCalculation: false,//强制刷新公式,公式较多时会有性能问题
    enableAddBackTop: false,//允许回到顶部
    enableAddRow: false, //底部是否显示添加多行
    showinfobar: false,//是否显示顶部信息栏
    showstatisticBar: false,//是否显示底部计数栏
    showstatisticBarConfig: {//自定义配置底部计数栏
        count: false, // 计数栏
        view: false, // 打印视图
        zoom: false // 缩放
    },
    showsheetbar: false,//是否显示底部sheet页按钮
    showsheetbarConfig: {//自定义底部sheet页按钮
        add: true, //新增sheet
        menu: false, //sheet管理菜单
        sheet: true //sheet页显示
    },
    sheetRightClickConfig: {//自定义配置sheet页右击菜单
        delete: true, // 删除
        copy: false, // 复制
        rename: true, //重命名
        color: false, //更改颜色
        hide: false, //隐藏，取消隐藏
        move: false //向左移，向右移
    },
    cellRightClickConfig: {
        copy: true, // 复制
        copyAs: false, // 复制为
        paste: true, // 粘贴
        insertRow: true, // 插入行
        insertColumn: true, // 插入列
        deleteRow: true, // 删除选中行
        deleteColumn: true, // 删除选中列
        deleteCell: false, // 删除单元格
        hideRow: false, // 隐藏选中行和显示选中行
        hideColumn: false, // 隐藏选中列和显示选中列
        rowHeight: false, // 行高
        columnWidth: false, // 列宽
        clear: true, // 清除内容
        matrix: false, // 矩阵操作选区
        sort: false, // 排序选区
        filter: false, // 筛选选区
        chart: false, // 图表生成
        image: false, // 插入图片
        link: false, // 插入链接
        data: true, // 数据验证
        cellFormat: false, // 设置单元格格式
        sysextends: true, //自定义扩展控件
        fileUpload: true, //自定义文件上传
        fileDownLoad: true //自定义文件下载
    },
    showtoolbar: false,//是否显示工具栏
    showtoolbarConfig: {//自定义工具栏
        undoRedo: true, //撤销重做，注意撤消重做是两个按钮，由这一个配置决定显示还是隐藏
        paintFormat: true, //格式刷
        currencyFormat: false, //货币格式
        percentageFormat: false, //百分比格式
        numberDecrease: false, // '减少小数位数'
        numberIncrease: false, // '增加小数位数
        moreFormats: true, // '更多格式'
        font: true, // '字体'
        fontSize: true, // '字号大小'
        bold: true, // '粗体 (Ctrl+B)'
        italic: true, // '斜体 (Ctrl+I)'
        strikethrough: true, // '删除线 (Alt+Shift+5)'
        underline: true, // '下划线 (Alt+Shift+6)'
        textColor: true, // '文本颜色'
        fillColor: true, // '单元格颜色'
        border: true, // '边框'
        mergeCell: true, // '合并单元格'
        horizontalAlignMode: true, // '水平对齐方式'
        verticalAlignMode: true, // '垂直对齐方式'
        textWrapMode: true, // '换行方式'
        textRotateMode: false, // '文本旋转方式'
        image:false, // '插入图片'
        link:false, // '插入链接'
        chart: false, // '图表'（图标隐藏，但是如果配置了chart插件，右击仍然可以新建图表）
        postil:  true, //'批注'
        pivotTable: false,  //'数据透视表'
        function: true, // '公式'
        frozenMode: false, // '冻结方式'
        sortAndFilter: false, // '排序和筛选'
        conditionalFormat: false, // '条件格式'
        dataVerification: true, // '数据验证'
        splitColumn: false, // '分列'
        screenshot: false, // '截图'
        findAndReplace: false, // '查找替换'
        protection:true, // '工作表保护'
        print:false // '打印'
    },
    hook:{
        cellEditBefore:function(cell){
            //校验单元格是否被保护
            checkProtectCell(cell);
            cellEditOper(cell);
        },
        rangeSelect:function(sheet,cell){
            protectCellSel(sheet,cell);
        },
        cellMousedown:function(cell){//鼠标释放钩子
            //校验单元格是否被保护
            checkProtectCell(cell);
        }
    }
};

var optionsDbMap = {
    lang: 'zh', // 设定表格语言
    container: 'luckysheet', //luckysheet为容器id
    title: 'dbmap', // 设定表格名称
    column: 16,//默认列数
    row: 20,//默认行数
    autoFormatw: false,//自动格式化超过4位数的数字为‘亿万格式’
    forceCalculation: false,//强制刷新公式,公式较多时会有性能问题
    enableAddBackTop: false,//允许回到顶部
    showinfobar: false,//是否显示顶部信息栏
    enableAddRow: false, //底部是否显示添加多行
    showstatisticBar: false,//是否显示底部计数栏
    showstatisticBarConfig: {//自定义配置底部计数栏
        count: false, // 计数栏
        view: false, // 打印视图
        zoom: false // 缩放
    },
    showsheetbar: false,//是否显示底部sheet页按钮
    showsheetbarConfig: {//自定义底部sheet页按钮
        add: false, //新增sheet
        menu: false, //sheet管理菜单
        sheet: true //sheet页显示
    },
    sheetRightClickConfig: {//自定义配置sheet页右击菜单
        delete: false, // 删除
        copy: false, // 复制
        rename: false, //重命名
        color: false, //更改颜色
        hide: false, //隐藏，取消隐藏
        move: false //向左移，向右移
    },
    cellRightClickConfig: {
        copy: false, // 复制
        copyAs: false, // 复制为
        paste: false, // 粘贴
        insertRow: false, // 插入行
        insertColumn: false, // 插入列
        deleteRow: false, // 删除选中行
        deleteColumn: false, // 删除选中列
        deleteCell: false, // 删除单元格
        hideRow: false, // 隐藏选中行和显示选中行
        hideColumn: false, // 隐藏选中列和显示选中列
        rowHeight: false, // 行高
        columnWidth: false, // 列宽
        clear: true, // 清除内容
        matrix: false, // 矩阵操作选区
        sort: false, // 排序选区
        filter: false, // 筛选选区
        chart: false, // 图表生成
        image: false, // 插入图片
        link: false, // 插入链接
        data: false, // 数据验证
        cellFormat: false, // 设置单元格格式
        sysextends: false, //自定义扩展控件
        fileUpload: false, //自定义文件上传
        fileDownLoad: false //自定义文件下载
    },
    showtoolbar: false,//是否显示工具栏
    hook:{
        cellEditBefore:function(cell){//编辑单元格钩子
            //校验单元格是否被保护
            checkProtectCell(cell);
            dbmapCellEditOper(cell);
        },
        cellMousedown:function(cell){//鼠标点击钩子
            currEditCellValue = cell;
        }
    }
};

var optionsFill = {
    lang: 'zh', // 设定表格语言
    container: 'luckysheet', //luckysheet为容器id
    title: 'fillinfo', // 设定表格名称
    column: 16,//默认列数
    row: 20,//默认行数
    autoFormatw: false,//自动格式化超过4位数的数字为‘亿万格式’
    forceCalculation: false,//强制刷新公式,公式较多时会有性能问题
    enableAddBackTop: false,//允许回到顶部
    showinfobar: false,//是否显示顶部信息栏
    enableAddRow: false, //底部是否显示添加多行
    showstatisticBar: false,//是否显示底部计数栏
    showstatisticBarConfig: {//自定义配置底部计数栏
        count: false, // 计数栏
        view: false, // 打印视图
        zoom: false // 缩放
    },
    showsheetbar: false,//是否显示底部sheet页按钮
    showsheetbarConfig: {//自定义底部sheet页按钮
        add: false, //新增sheet
        menu: false, //sheet管理菜单
        sheet: true //sheet页显示
    },
    sheetRightClickConfig: {//自定义配置sheet页右击菜单
        delete: false, // 删除
        copy: false, // 复制
        rename: false, //重命名
        color: false, //更改颜色
        hide: false, //隐藏，取消隐藏
        move: false //向左移，向右移
    },
    cellRightClickConfig: {
        copy: false, // 复制
        copyAs: false, // 复制为
        paste: false, // 粘贴
        insertRow: false, // 插入行
        insertColumn: false, // 插入列
        deleteRow: false, // 删除选中行
        deleteColumn: false, // 删除选中列
        deleteCell: false, // 删除单元格
        hideRow: false, // 隐藏选中行和显示选中行
        hideColumn: false, // 隐藏选中列和显示选中列
        rowHeight: false, // 行高
        columnWidth: false, // 列宽
        clear: true, // 清除内容
        matrix: false, // 矩阵操作选区
        sort: false, // 排序选区
        filter: false, // 筛选选区
        chart: false, // 图表生成
        image: false, // 插入图片
        link: false, // 插入链接
        data: false, // 数据验证
        cellFormat: false, // 设置单元格格式
        sysextends: false, //自定义扩展控件
        fileUpload: false, //自定义文件上传
        fileDownLoad: false //自定义文件下载
    },
    showtoolbar: false,//是否显示工具栏
    hook:{
        cellEditBefore:function(cell){
            //校验单元格是否被保护
            checkProtectCell(cell);
            cellEditOper(cell);
        },
        cellMousedown:function(cell){    //鼠标释放钩子
            //校验单元格是否被保护
            checkProtectCell(cell);
        },
        sheetActivate:function(index, isPivotInitial, isNewSheet){  //激活工作表前,用户工作表切换的钩子
            // {Number} [i]: sheet页的index,与order区分开
            // {Boolean} [isPivotInitial]: 是否切换到了数据透视表页
            // {Boolean} [isNewSheet]: 是否新建了sheet页
            // console.info(index, isPivotInitial, isNewSheet);

            timerShowValue();
        }
    }
};

var optionsView = {
    lang: 'zh', // 设定表格语言
    container: 'luckysheet', //luckysheet为容器id
    title: 'view', // 设定表格名称
    column: 16,//默认列数
    row: 20,//默认行数
    autoFormatw: false,//自动格式化超过4位数的数字为‘亿万格式’
    forceCalculation: false,//强制刷新公式,公式较多时会有性能问题
    enableAddBackTop: false,//允许回到顶部
    showinfobar: false,//是否显示顶部信息栏
    enableAddRow: false, //底部是否显示添加多行
    showstatisticBar: false,//是否显示底部计数栏
    showstatisticBarConfig: {//自定义配置底部计数栏
        count: false, // 计数栏
        view: false, // 打印视图
        zoom: false // 缩放
    },
    showsheetbar: false,//是否显示底部sheet页按钮
    showsheetbarConfig: {//自定义底部sheet页按钮
        add: false, //新增sheet
        menu: false, //sheet管理菜单
        sheet: true //sheet页显示
    },
    sheetRightClickConfig: {//自定义配置sheet页右击菜单
        delete: false, // 删除
        copy: false, // 复制
        rename: false, //重命名
        color: false, //更改颜色
        hide: false, //隐藏，取消隐藏
        move: false //向左移，向右移
    },
    cellRightClickConfig: {
        copy: false, // 复制
        copyAs: false, // 复制为
        paste: false, // 粘贴
        insertRow: false, // 插入行
        insertColumn: false, // 插入列
        deleteRow: false, // 删除选中行
        deleteColumn: false, // 删除选中列
        deleteCell: false, // 删除单元格
        hideRow: false, // 隐藏选中行和显示选中行
        hideColumn: false, // 隐藏选中列和显示选中列
        rowHeight: false, // 行高
        columnWidth: false, // 列宽
        clear: false, // 清除内容
        matrix: false, // 矩阵操作选区
        sort: false, // 排序选区
        filter: false, // 筛选选区
        chart: false, // 图表生成
        image: false, // 插入图片
        link: false, // 插入链接
        data: false, // 数据验证
        cellFormat: false, // 设置单元格格式
        sysextends: false, //自定义扩展控件
        fileUpload: false, //自定义文件上传
        fileDownLoad: false //自定义文件下载
    },
    showtoolbar: false,//是否显示工具栏
    hook:{
        cellEditBefore:function(cell){
            return false;
            //校验单元格是否被保护
            // checkProtectCell(cell);
            // dbmapCellEditOper(cell);
        },
        cellMousedown:function(cell){//鼠标释放钩子
            // return false;
            //校验单元格是否被保护
            // checkProtectCell(cell);
        },
        sheetActivate:function(index, isPivotInitial, isNewSheet){//激活工作表前,用户工作表切换的钩子
            // {Number} [i]: sheet页的index,与order区分开
            // {Boolean} [isPivotInitial]: 是否切换到了数据透视表页
            // {Boolean} [isNewSheet]: 是否新建了sheet页
            // console.info(index, isPivotInitial, isNewSheet);

            timerShowValue();
        }
    }
};

function exportFillExcel(){
    var action = serveraddr + "/reportfill/export/excel";

    var $form = $("<form id='wjxzform' enctype='application/x-www-form-urlencoded' class='hidden' method='post'></form>");
    $form.attr("action",action);
    $(document.body).append($form);

    var $input1 = $("<input id='sheetInfo' name='sheetInfo' type='text'></input>");
    $input1.attr("value",JSON.stringify(luckysheet.getAllSheets()));
    $("#wjxzform").append($input1);

    $form.submit().remove();
}

function protectCellSel(sheet,cell){
    if(protectFormFlag){
        $('#protectCellId').val(luckysheet.getRangeAxis());
    }
}

function checkProtectCell(cell){
    if(protectCellData!=null){
        if(protectCellData.hasOwnProperty(luckysheet.getSheet().name)){
            let data = new Array();
            data = protectCellData[luckysheet.getSheet().name].split(',');
            let checkData = [];
            for (let i = 0; i < data.length; i++) {
                if(data[i].indexOf(":") > -1){
                     let showData = showCellArea(data[i]);
                     checkData.push(...showData)
                }else{
                    checkData.push(data[i]);
                }
            }
            if(checkData.indexOf(luckysheet.getRangeAxis().toString()) > -1){
                layer.alert('受保护单元格，不可编辑！');
                return false;
            }
            //受保护--合并单元格--的校验
            if(data.indexOf(luckysheet.getRangeAxis().toString()) > -1){
                layer.alert('受保护单元格，不可编辑！');
                return false;
            }
        }
    }
}

/**
 * 根据celldata数组中的值，回显sheet页中cell的显示值m和实际值v
 */
function timerShowValue(){
    var num = 1;
    var timer = setInterval(function () {
        num++;
        if(celldata!=null&&celldata.length>0&&num>3){
            for(let i=0;i<celldata.length;i++){
                for(let a=0;a<celldata[i].length;a++){
                    let cell = celldata[i][a];
                    if((cell.v.m!=cell.v.v)&&(cell.v.ct.t!='d')){
                        let row_focus = Number(cell.r);
                        let column_focus = Number(cell.c);
                        let cellUpdate = {
                            "v": cell.v.v, //内容的原始值
                            "m": cell.v.m, //内容的显示值
                        };
                        luckysheet.setCellValue(row_focus,column_focus,cellUpdate,{order: i, isRefresh: true});
                    }
                }
            }
            clearInterval(timer);
        }
        if (num >= 20) {
            clearInterval(timer);
        }
    }, 5);
}
